<template>
  <div class="mon-box">
    <div class="tab_control">
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane label="视频监控" name="1" >
          <div class="content-box" v-if="activeName == 1">
            <article>
              <div class="video" v-for="(item, index) in videoDataList" :key="item.id">
                <video class="video-js vjs-default-skin" width="100%" height="100%" controls>
                  <source :src="item.deviceUrl" type="application/x-mpegURL" />
                </video>
                <div class="replay-icon" v-show="item.isShowRefresh">
                  <el-button icon="el-icon-refresh-right" circle @click="replayVideo(item.deviceUrl, index)" />
                </div>
                <div class='device-name'>视频：{{ item.deviceCnName }}</div>
                <div class="hint-text" v-show="!item.deviceUrl">未获取到视频监控</div>
              </div>
            </article>

            <aside v-if="showControlPanel">
              <div class="control-container">
                <div style="position: relative;">
                  <div class="title">方向控制</div>
                  <div style="position: absolute; right: 0px; top: -6px; display: flex; align-items: center;">
                    <span style="font-size: 14px; color: #333;">视频源：</span>
                    <el-select
                      v-model="videoId"
                      style="width: 170px;"
                      size="small"
                      clearable
                      placeholder="请选择视频"
                      @change="selectVideo(videoId)">
                      <el-option v-for="item in videoDataList" :key="item.id" :label="item.deviceCnName" :value="item.id" />
                    </el-select>
                  </div>
                  <div class="direction">
                    <i class="icon iconfont icon-zuo" :class="[num == 1 ? 'active' : '']" @click.prevent="directionControl(1)"></i>
                    <i class="icon iconfont icon-you" :class="[num == 2 ? 'active' : '']" @click.prevent="directionControl(2)"></i>
                    <i class="icon iconfont icon-shang" :class="[num == 3 ? 'active' : '']" @click.prevent="directionControl(3)"></i>
                    <i class="icon iconfont icon-xia" :class="[num == 4 ? 'active' : '']" @click.prevent="directionControl(4)"></i>
                    <i class="round" :class="[num == 0 ? 'active' : '']" @click.prevent="directionControl(0)">停止</i>
                  </div>
                </div>

                <div class="control-top">
                  <div class="title">焦距控制</div>
                  <div class="play-speed-box" style="margin-top: 16px">
                    <div>
                      <el-button size="small" style="width: 100px" @click.prevent="controlZoom(1)">放大 <span>+</span></el-button>
                      <el-button size="small" style="width: 100px" @click.prevent="controlZoom(2)">缩小 <span>-</span></el-button>
                    </div>
                  </div>
                </div>
              </div>
            </aside>
          </div>
        </el-tab-pane>

        <el-tab-pane label="视频源列表" name="2">
          <MonitorList ref='MonitorListRef' @emitInfo='addVideoInfo'></MonitorList>
        </el-tab-pane>
      </el-tabs>
    </div>

    <div class="button_box">
      <el-row>
        <span v-show='activeName == 1'>
          <span style="font-size: 14px; color: #333;">标段:</span>
          <el-select v-model="bidSection" size="mini" class="select-width" clearable placeholder="请选择标段" @change="getWorkAreaList">
            <el-option v-for="item in biaoduanList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>

          <span style="font-size: 14px; color: #333; margin-left: 12px;">工区:</span>
          <el-select v-model="areaId" size="mini" class="select-width" clearable placeholder="请选择工区" @change="getVideoList">
            <el-option v-for="item in workAreaInfo" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </span>

        <el-button type="text" icon="el-icon-refresh" plain @click="refreshListData">刷新</el-button>
        <el-button type="text" :icon="icon" plain v-show='activeName == 2' @click="addVideoInfo(null)">添加视频源</el-button>
      </el-row>
    </div>

    <el-pagination
      class="page"
      background
      v-if="activeName == 1"
      @current-change="handleCurrentChange"
      layout="prev, pager, next, total"
      :current-page.sync="pageData.pageNum"
      :page-size="pageData.pageSize"
      :total="pageData.total">
    </el-pagination>

    <AddMonitorInfo ref="AddMonitorInfoRef"></AddMonitorInfo>
  </div>
</template>

<script>
import MonitorList from "./monitor/MonitorList";
import AddMonitorInfo from "./monitor/AddMonitorInfo";
import HttpInterface from '../../util/httpInterface';
import httpConfig from "../../util/httpConfig";
import Qs from 'qs';
import axios from 'axios';
import { mapActions, mapState } from "vuex";
import { randomString } from "../../util/utils";

export default {
  components: {
    MonitorList, AddMonitorInfo
  },
  data() {
    return {
      activeName: '1',
      icon: "el-icon-circle-plus-outline",
      videoDataList: [],
      workAreaInfo: [],
      myPlayer: [],
      areaId: "",
      showControlPanel: true,
      bidSection: "",
      videoId: "",
      num: -1,
      pageData: {
        total: 0,
        pageNum: 1,
        pageSize: 4
      },
      playValue: "",
      deviceType: 2,
      // 乐橙云接口参数
      system: {
        "ver": "1.0",
        "appId": "lc084417e80a6046c8",
        "sign": "",
        "time": "",
        "nonce": ""
      },
      appSecret: "528d3acf972a4b648e1a0bf3eae4e7",
      id: "18e3543b-4a5d-4a55-b25d-d9018af9b901",
      channelId: "0",
      deviceId: "",
      level: 0,
      vertical: 0,
      zoom: 0,
      // 萤石接口参数
      appKey: "783c2cb70b284252ac4a694fa713aff2",
      secret: "5339c1f9d56e3b503fc5e06313fae9fd",
      tokenInfo: {},  // 获取的token信息
      deviceSerial: "",   // 设备序列号
      channelNo: 1,   // 通道号
      speed: 1,    // 云台速度：0-慢，1-适中，2-快，海康设备参数不可为0
      options: {
        language: 'zh-CN',  // 设置语言
        controls: true,  //是否显示控制条
        autoplay: false,  // 自动播放开关
        preload: "auto",
        fluid: false,  // 自适应宽高
        controlBar: {
          playToggle: true,
          children: [
            {name: 'playToggle'}, // 播放按钮
            {name: 'currentTimeDisplay'}, // 当前已播放时间
            {name: 'progressControl'}, // 播放进度条
            {name: 'durationDisplay'}, // 总时间
            {name: 'FullscreenToggle'}, // 全屏
            {
              name: 'volumePanel', // 音量控制
              inline: false, // 不使用水平方式
            },
          ]
        }
      }
    };
  },

  computed: {
    ...mapState(["biaoduanList"])
  },

  mounted() {
    this.systemRandom(() => {
      this.getLechangeToken();
    });
    this.getLappToken();
    HttpInterface.getUserInfo(() => {
      this.getTendersInfo();
      this.getWorkAreaInfo();
      this.getVideoList();
    })
  },

  beforeDestroy() {
    this.disposeVideo();
  },

  methods: {
    ...mapActions(["getTendersInfo", "getWorkAreaInfo", "selectByBidSection"]),

    disposeVideo() {
      let len = this.myPlayer.length;
      if (len > 0) {
        for (let i = 0; i < len; i++) {
          let item = this.myPlayer[i];
          item.player_ && item.dispose();
        }
        this.rtmpArr = [];
      }

      this.flag = null;
    },

    initVideo() {
      let _this = this;
      this.$nextTick(() => {
        this.myPlayer = [];
        let video = document.getElementsByClassName("video-js");

        this.videoDataList.forEach((item, index) => {

          this.myPlayer[index] = this.$video(video[index], this.options, function onPlayerReady () {
            this.on('error', function() {
              console.log("请求数据时遇到错误")
            });

            this.on("ended", function(event) {
              item.isShowRefresh = true;
              console.log("视频播放结束");
            });

            this.on('play', () => {
              item.isShowRefresh = false;
              console.log("开始播放")
            });

            this.on('pause', function() {
              console.log("暂停播放")
            });
          }, this);

        })
      });
    },

    replayVideo(url, index) {
      this.flag = setTimeout(() => {
        this.myPlayer[index].src({ type: "application/x-mpegURL", src: url });
        this.myPlayer[index].load(url);
        this.myPlayer[index].play();
      }, 200)
    },

    // 获取视频信息
    getVideoList() {
      let { bidSection, pageData, areaId } = this;
      let _this = this;
      var params = {
        page: pageData.pageNum,
        size: pageData.pageSize
      }
      if (bidSection) params.bidSection = bidSection;
      if (areaId) params.areaId = areaId;
      HttpInterface.requestGet(this, HttpInterface.UEL_FIND_PAGE, params, function (response) {
        var data = response.data;
        if (data.success) {
          var { rows, total } = data.other;
          _this.videoDataList = _this.renderData(rows);
          _this.pageData.total = total;
          _this.initVideo();
        } else {
          _this.errorMessage(data.msg);
        }
      }, function(err) {
        _this.errorMessage("请求数据失败！");
      })
    },

    renderData(arr) {
      arr.forEach(item => {
        var str = "";
        // 判断字符串中是否有 'dev_'
        if (item.deviceUrl.indexOf('dev_') != -1) {
          item.deviceUrl.replace(/(dev_)/g, function () {
            for (let i = 0; i < arguments.length; i++) {
              var num = arguments[2] + arguments[1].length;
              str = arguments[3].slice(num, num + 15);
            }
          })
        }
        item.isShowRefresh = false;
        if (str != "") {
          item.deviceId = str;
        } else {
          item.deviceId = null;
        }
      })
      return arr;
    },

    // 获取工区
    getWorkAreaList() {
      let _this = this;
      this.areaId = "";
      this.selectByBidSection({
        bidSection: this.bidSection,
        fn: function (data) {
          _this.workAreaInfo = data;
          _this.getVideoList();
        }
      })
    },


    // 选择要播放的视频
    selectVideo(id) {
      this.videoDataList.forEach(item => {
        if (item.id == id) {
          this.deviceId = item.deviceId;
          this.deviceType = item.deviceType;
          this.deviceSerial = item.deviceKey;
        }
      })
      this.showControlPanel = true;
    },

    // 标签切换
    handleClick() {
      this.refreshListData();
    },

    // 刷新数据
    refreshListData () {
      switch (this.activeName) {
        case "1":
          this.getVideoList();
          break;
        case "2":
          this.disposeVideo();
          this.$refs.MonitorListRef.getMonitorList();
          break;
      }
    },

    // 添加视频源
    addVideoInfo(id) {
      if (id) {
        this.$refs.AddMonitorInfoRef.show(id);
      } else {
        this.$refs.AddMonitorInfoRef.show();
      }
    },

    // 分页
		handleCurrentChange(val) {
      this.disposeVideo();
      this.pageData.pageNum = val;
      this.videoId = "";
      this.getVideoList();
    },

    // 视频方向控制
    directionControl(index) {
      if (!this.videoId) return this.warningMessage("请选择需要控制的视频");
      var _this = this;
      this.num = index;
      var number = 0;
      if (this.deviceType == 1) {
        switch (index) {
          case 0:
            number = 10;
            break;
          case 1:
            number = 2;
            break;
          case 2:
            number = 3;
            break;
          case 3:
            number = 0;
            break;
          case 4:
            number = 1;
            break;
        }
        this.systemRandom(function () {
          _this.cameraControl(number);
        });
      } else {
        switch (index) {
          case 1:
            number = 2;
            this.lastIndex = 2;
            break;
          case 2:
            number = 3;
            this.lastIndex = 3;
            break;
          case 3:
            number = 0;
            this.lastIndex = 0;
            break;
          case 4:
            number = 1;
            this.lastIndex = 1;
            break;
          case 0:
            number = null;
            break;
        }
        this.commandDirection(number);
      }
    },

    // 视频变焦控制
    controlZoom(index) {
      if (!this.videoId) return this.warningMessage("请选择需要控制的视频");
      var _this = this;
      var number = 0;
      if (this.deviceType == 1) {
        if (index == 1) {
          number = 8;
          this.systemRandom(function () {
            _this.cameraControl(number);
          });
        } else if (index == 2) {
          number = 9;
          this.systemRandom(function () {
            _this.cameraControl(number);
          });
        }
      } else {
        if (index == 1) {
          number = 8;
          this.commandDirection(number);
        } else if (index == 2) {
          number = 9;
          this.commandDirection(number);
        }
      }
    },

    // 控制摄像头方向
    cameraControl(num) {
      var _this = this;
      var data = {
        system: this.system,
        params: {
          token: this.accessToken,
          deviceId: this.deviceId,
          channelId: this.channelId,
          operation: num,
          duration: num == 8 || num == 9 ? 1000 : 400
        },
        id: this.id
      }
      HttpInterface.requestPOST(this, HttpInterface.URL_CONTROL_MOVE_PTZ, data, function (res) {
        var data = res.data;
        console.log("乐橙云 方向或变焦控制：", data.result);
      }, null, false)
    },

    // 获取乐橙云token
    getLechangeToken() {
      var _this = this;
      var data = {
        system: this.system,
        params: {},
        id: this.id
      }
      HttpInterface.requestPOST(this, HttpInterface.URL_ACCESS_TOKEN, data, function (res) {
        var { result } = res.data;
        if (result.code == 0) {
          _this.accessToken = result.data.accessToken;
        }
      }, function (err) {
        console.log(err.response);
      }, false)
    },

    // 乐橙云system数据
    systemRandom(callback) {
      this.system.nonce = randomString();
      this.system.time = parseInt(new Date().getTime() / 1000);
      let { appSecret } = this;
      let { time, nonce } = this.system;

      var obj = JSON.stringify({ time, nonce, appSecret });
      var sign = obj.replace(/\{/g,"").replace(/}/g,"").replace(/\"/g,"");
      this.system.sign = this.$md5(sign);
      callback();
    },




    // 萤石接口
    getLappToken() {
      let pash = httpConfig.lappUrl + HttpInterface.URL_LAPP_TOKEN_GET;
      let url = pash + `?appKey=${this.appKey}&appSecret=${this.secret}`;
      let options = {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        url,
      };
      axios(options).then(res => {
        let data = res.data;
        if (data.code == 200) {
          this.tokenInfo = data.data;
        }
      }).catch(err => {
        console.log(err.response);
      });
    },

    // 控制摄像头方向
    commandDirection(number) {
      let pash = httpConfig.lappUrl + HttpInterface.URL_LAPP_DEVICE_PTZ_START;
      let url = pash + `?appKey=${this.appKey}&appSecret=${this.secret}`;
      let params = {
        accessToken: this.tokenInfo.accessToken,
        deviceSerial: this.deviceSerial,
        channelNo: this.channelNo,
        direction: number,
        speed: this.speed
      }
      let options = {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        data: Qs.stringify(params),
        url,
      };
      axios(options).then(res => {
        let data = res.data;
        console.log("萤石 方向或变焦控制：", data);
        if (data.code == 200) {
          setTimeout(() => {
            this.stopDirection();
          }, 600);
        } else {
          this.errorMessage(data.msg);
        }
      }).catch(err => {
        console.log(err.response);
      });
    },

    // 萤石 停止方向
    stopDirection() {
      let pash = httpConfig.lappUrl + HttpInterface.URL_LAPP_DEVICE_PTZ_STOP;
      let url = pash + `?appKey=${this.appKey}&appSecret=${this.secret}`;
      let params = {
        accessToken: this.tokenInfo.accessToken,
        deviceSerial: this.deviceSerial,
        channelNo: this.channelNo,
        direction: this.lastIndex
      }
      let options = {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        data: Qs.stringify(params),
        url,
      };
      axios(options).then(res => {
        let data = res.data;
        console.log("萤石 停止操作：", data);
        if (data.code != 200) {
          this.errorMessage(data.msg);
        }
      })
    }
  }
};
</script>

<style scoped lang="scss">
*{
  box-sizing: border-box;
}

.content-box{
  width: 100%;
  height: calc(100vh - 142px);
  margin-top: 80px;
  padding: 0 20px 20px 20px;
  display: flex;
  justify-content: space-between;
}

article {
  width: 70%;
  height: 100%;
  display: flex;
  flex-wrap: wrap;

  .video {
    width: calc(50% - 16px);
    height: calc(50% - 20px);
    background: #dfdfdf;
    border: 2px solid #dfdfdf;
    margin-right: 30px;
    margin-bottom: 30px;
    transition: all .3s;
    position: relative;

    &:nth-child(2n) {
      margin-right: 0;
    }

    .device-name{
      color: #2976c4;
      text-align: center;
      margin-top: 2px;
      font-size: 14px;
    }

    .hint-text{
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      z-index: 200;
      font-size: 14px;
      color: rgba(255, 255, 255, 0.5);
    }

    .replay-icon{
      position: absolute;
      left: 0;
      top: 0;
      z-index: 500;
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      background: rgba(0, 0, 0, 0.7);
    }
  }

  &.active {
    border: 2px solid #4688cc;
  }
}


aside {
  width: 26%;
  height: 100%;
  background: #fff;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
  border-radius: 10px;
}

.mon-box .page {
  margin: 10px 0 20px 0;
  text-align: center;
}

.control-container {
  width: 100%;
  height: calc(100% - 42px);
  padding: 20px;
  margin-top: 10px;

  .title {
    font-size: 16px;
  }

  .direction {
    margin: 14px auto;
    width: 280px;
    height: 280px;
    position: relative;
    background: url(../images/play-btn-bg.png) no-repeat left top / 100% 100%;

    .round {
      width: 60px;
      height: 60px;
      border-radius: 50%;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 14px;
      color: #d0d0d0;
      position: absolute;
      left: 50%;
      top: 95px;
      transform: translate(-50%);
      cursor: pointer;
      transition: all .3s;

      &.active {
        color: #fc82ff;
      }
    }

    .icon-zuo,
    .icon-you,
    .icon-shang,
    .icon-xia {
      position: absolute;
      font-size: 20px;
      color: #d0d0d0;
      cursor: pointer;
      transition: all .3s;
    }

    .icon-zuo.active,
    .icon-you.active,
    .icon-shang.active,
    .icon-xia.active {
      color: #fc82ff;
      cursor: pointer;
    }

    .icon-zuo {
      left: 74px;
      top: 114px;
    }

    .icon-you {
      right: 74px;
      top: 114px;
    }

    .icon-shang {
      left: 50%;
      top: 58px;
      transform: translate(-50%);
    }

    .icon-xia {
      left: 50%;
      top: 170px;
      transform: translate(-50%);
    }
  }

  .control-top {
    .play-speed-box {
      margin-left: 60px;
      margin-top: 10px;

      .text {
        font-size: 14px;
        margin-right: 12px;
      }
    }
  }
}

.select-width{
  width: 120px;
}

// 视频中的刷新按扭
.is-circle {
  padding: 20px;
  background: rgba(0, 0, 0, 0.4);
  border: 2px solid #ffffff;
  font-size: 24px;
  color: #ffffff;
}
</style>

<style scoped>
/* 视频流样式 */
.video-js {
  width: 100% !important;
  height: 100% !important;
}

.video-js >>> .vjs-big-play-button {
  width: 70px;
  height: 70px;
  left: 50%;
  top: 50%;
  border-radius: 50%;
  transform: translate(-50%, -50%);
}

.video-js .vjs-time-control {
  display: block;
}

.video-js .vjs-remaining-time {
  display: none;
}


.video-js >>> .vjs-big-play-button .vjs-icon-placeholder:before {
  content: "\F101";
  line-height: 66px;
  border-radius: 2px;
}

.vjs-error >>> .vjs-error-display .vjs-modal-dialog-content {
  display: none;
}

.vjs-error >>> .vjs-error-display:before {
  content: "";
}

.el-pagination >>> button.btn-prev,
.el-pagination >>> button.btn-next {
  color: rgba(0, 0, 0, .65);
  border: 1px solid #e5e5e5;
  background: #fff;
}

.el-pagination.is-background >>> .el-pager li {
  border: 1px solid #e5e5e5;
  background: #fff;
  line-height: 26px;
  transition: arr .3s;
}

.el-pagination.is-background >>> .el-pager li.active {
  color: #fff;
  background-color: #4688cc;
  border-color: #4688cc;
}

.el-pagination.is-background >>> .el-pager li:not(.active):hover {
  border-color: #4688cc;
  color: #4688cc;
}
</style>
